import {getAreas, getSetFields, updateMemberField} from '../../api/member.js';
import Util from '../../utils/util.js';
import Status from '../../utils/status.js';

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {

    dialog3: false,
    iosDialog1: false,

    dialog_fields: {
      height: {
        title: "身高(CM)",
        from: Status.memberHeight(),
        to: Status.memberHeight(),
      },
      birth: {
        title: "出生日期",
        from: Status.memberBirthday(),
        to: Status.memberBirthday(),
      },
    },

    current_area_index: 0,
    current_dialog_index: "height"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this

    that.setData({
      bottom: app.globalData.footerPadding
    })

    wx.showLoading({
      title: '正在加载',
    })

    let dialog_fields = that.data.dialog_fields
    getSetFields().then(res => {
      that.setData(res.data)
      that.setData({dialog_fields: dialog_fields})
      wx.hideLoading()
    }).catch(errmsg => {
      return app.Tips({title: errmsg}, {tab: 3})
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  bindChange(e) {
    let fields = this.data.fields;
    if (!e.target.id) {
      return;
    }
    fields[e.target.id].default_val = e.detail.value;

    const that = this
    wx.showLoading({title: '正在更新...'})
    updateMemberField({
      field_key: e.target.id,
      [e.target.id]: e.detail.value
    }).then(res => {
      that.setData({
        fields: fields
      });
      wx.hideLoading()
    }).catch(errmsg => {
      app.Tips({title: errmsg})
    })

  },

  showSelectArea(e) {
    const that = this
    let areas = wx.getStorageSync("areas");
    if (!areas) {
      getAreas().then(res => {
        wx.setStorageSync('areas', res.data.areas);

        that.setData(res.data)
        that.selectProvince(e, 0)
      }).catch(errmsg => {
        app.Tips({title: errmsg})
      })
    } else {
      that.setData({areas: areas})
      this.selectProvince(e, 0)
    }
    this.setData({
      dialog3: true
    });
  },

  showSelectDialog(e) {
    const that = this,
      key = e.currentTarget.dataset.key

    that.setData({
      current_dialog_index: key,
      iosDialog1: true
    })

  },

  selectCity(e) { //选择城市
    const that = this,
      key = e.currentTarget.dataset.key

    let fields = that.data.fields,
      areas = that.data.areas

    let current_city = areas[that.data.current_area_index]._child,
      acept_city = []
    if (fields['accept_city'].default_val) {
      acept_city = fields['accept_city'].default_val.split(" ");
    }

    if (current_city[key].class) { //去掉
      current_city[key].class = ""
      acept_city.splice(acept_city.indexOf(current_city[key].title), 1);
    } else {
      acept_city.push(current_city[key].title)
      current_city[key].class = "active"
    }

    fields['accept_city'].default_val = acept_city.join(" ")
    areas[that.data.current_area_index]._child = current_city

    wx.showLoading({
      title: '正在更新...',
    })
    updateMemberField({
      field_key: "accept_city",
      "accept_city": fields['accept_city'].default_val
    }).then(res => {
      that.setData({
        areas: areas,
        fields: fields
      })
      wx.hideLoading()
    }).catch(errmsg => {
      app.Tips({title: errmsg})
    })
  },

  selectProvince(e, val = 0) {
    const that = this,
      key = e.currentTarget.dataset.key || val

    let fields = that.data.fields,
      areas = that.data.areas

    let acept_city = fields['accept_city'].default_val || '';

    if (acept_city) {
      acept_city = acept_city.split(" ")
    }

    for (const k in areas[key]._child) {
      if (acept_city.indexOf(areas[key]._child[k].title) === -1) continue;
      areas[key]._child[k]['class'] = "active";
    }
    this.setData({
      areas: areas,
      current_area_index: key
    })
  },

  close: function () {
    this.setData({
      dialog3: false,
      iosDialog1: false
    });
  },

  goPage(e) {
    wx.navigateTo({
      url: "../" + e.currentTarget.dataset.url
    })
  },

  changeSwitch(e) {
    const that = this,
      key = e.currentTarget.dataset.key

    let fields = that.data.fields
    const v = (fields[key].default_val == 1) ? 0 : 1;
    let tips = {
      //open_share: { content: '关闭后他人无法打开你朋友圈或公众号推送资料链接（不影响互选池），确定关闭吗?',  title: '关闭推送资料链接访问'},
      // homosex_visibility: { content: '开启后同性将能访问你公众号或朋友圈推送链接，确定开启吗?',  title: '开启同性访问推送资料'},
      // enlist_need_verify_profile: { content: '开启后应征者应征我将需要提交学历审核通过后才能应征，应征者可能会减少，确定开启吗?',  title: '开启应征要审核'},
      accept_enlist_message: {content: '关闭后所有互选池新成员加入都不提醒我，确定关闭吗?', title: '新成员加入互选池提醒我'},
      is_send_visit_msg: {content: '关闭后来访人员都不提醒我，确定关闭吗?', title: '来访人员接待提醒'},
      is_nearby: {content: '退出后附近的人看不到你。退出后若再点附近的人会自动加入。', title: '退出附近的人提醒'},
      is_offline: {content: '关闭后对方将看到你的来访记录', title: '关闭会员隐身访问'},
    }

    if (tips[key]) {
      if (v == 0) {//显示提醒
        Util.showModelTip(tips[key].content, tips[key].title, "确定").then(res => {
          if (res.confirm) {
            that.updateMemberField(fields, key, v)
          } else {
            that.setData({fields: fields})
          }
        })
      } else {// 不显示提醒
        that.updateMemberField(fields, key, v)
      }
      return
    }
  },
  updateMemberField(fields, key, v) {
    const that = this
    fields[key].default_val = v
    wx.showLoading({
      title: '正在更新...',
    })
    updateMemberField({
      field_key: key,
      [key]: v
    }).then(res => {
      that.setData(fields)
      wx.hideLoading()
    }).catch(errmsg => {
      app.Tips({title: errmsg})
    })
  },
  bindDialogChange(e) {
    const that = this,
      id = e.target.id,
      v = e.detail.value,
      current_dialog_index = that.data.current_dialog_index
    let dialog_fields = that.data.dialog_fields
    dialog_fields[current_dialog_index]['default_val_' + id] = v

    this.setData({
      dialog_fields: dialog_fields
    })
  },

  submitHeightBirth(e) {
    const that = this,
      dialog_fields = that.data.dialog_fields,
      current_dialog_index = that.data.current_dialog_index


    let form_data = {}
    form_data[current_dialog_index + '_to'] = dialog_fields[current_dialog_index]['default_val_to'] ? dialog_fields[current_dialog_index].to[dialog_fields[current_dialog_index]['default_val_to']] : ''
    form_data[current_dialog_index + '_from'] = dialog_fields[current_dialog_index]['default_val_from'] ? dialog_fields[current_dialog_index].from[dialog_fields[current_dialog_index]['default_val_from']] : ''

    if (form_data[current_dialog_index + '_to'] != "" && form_data[current_dialog_index + '_from'] != "不限" && form_data[current_dialog_index + '_to'] <= form_data[current_dialog_index + '_from']) {
      app.Tips({title: "起始不能比截止大"});
      return
    }

    wx.showLoading({
      title: '正在更新...',
    })
    let fields = that.data.fields;
    fields[current_dialog_index].default_val_to = dialog_fields[current_dialog_index]['default_val_to'] ? parseInt(dialog_fields[current_dialog_index]['default_val_to']) : ''
    fields[current_dialog_index].default_val_from = dialog_fields[current_dialog_index]['default_val_from'] ? parseInt(dialog_fields[current_dialog_index]['default_val_from']) : ''

    fields[current_dialog_index].default_val_to = fields[current_dialog_index].default_val_to - 1;
    fields[current_dialog_index].default_val_from = fields[current_dialog_index].default_val_from - 1;

    updateMemberField(form_data)
      .then(res => {
        that.setData({
          fields: fields,
          iosDialog1: false
        })
        wx.hideLoading()
      }).catch(errmsg => {
      app.Tips({title: errmsg})
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    wx.removeStorageSync('areas')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})